<template >
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input placeholder="请输入内容" clearable @clear="getUsers" v-model="queryInfo.query">
            <el-button slot="append" @click="getUsers" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="onShowAddDialog">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="usersData" stripe border style="width: 100%">
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="onStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="onShowEditDialog(scope.row.id)"
              icon="el-icon-edit"
            ></el-button>
            <el-button
              type="danger"
              @click="onRemoveUser(scope.row.id)"
              size="mini"
              icon="el-icon-delete"
            ></el-button>
            <el-button
              type="warning"
              @click="onShowSetRoleDialog(scope.row)"
              size="mini"
              icon="el-icon-setting"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[1, 2, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>
    <el-dialog title="提示" :visible.sync="isAddDialog" width="60%" :before-close="closeAddDialog">
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="80px">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeAddDialog">取 消</el-button>
        <el-button type="primary" @click="onAddUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="修改用户"
      :visible.sync="isEditDialog"
      width="60%"
      :before-close="closeEditDialog"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeEditDialog">取 消</el-button>
        <el-button type="primary" @click="onEditUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="设置角色" :visible.sync="isSetRoleDialog" width="60%" :close="closeSetRoleDialog">
      <div>
        <p>当前的用户: {{userInfo.username}}</p>
        <p>当前的角色: {{userInfo.role_name}}</p>
        <div>
          分配新角色:
          <el-select @change="onChangeRole" v-model="selectRole" placeholder="请选择">
            <el-option v-for="item in roles" :key="item.id" :label="item.roleName" :value="item.id"></el-option>
          </el-select>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeSetRoleDialog">取消</el-button>
        <el-button type="primary" @click="onSetRole">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  created() {
    this.getUsers()
  },
  data() {
    // 手机号验证规则
    let validateMobile = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      let mobileReg = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/
      if (!mobileReg.test(value)) {
        return callback(new Error('手机号格式不正确'))
      }
      callback()
    }
    // 邮箱验证
    let validateEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('邮箱不能为空'))
      }
      let emialReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+\.([a-zA-Z0-9_-])+$/
      if (!emialReg.test(value)) {
        return callback(new Error('邮箱格式不正确'))
      }
      callback()
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 操作的用户信息
      userInfo: {},
      // 角色容器
      roles: null,
      // 操作的角色
      selectRole: null,
      // 用户列表
      usersData: null,
      // 总条数
      total: 0,
      // 是否显示添加用户对话框
      isAddDialog: false,
      // 是否显示编辑用户对话框
      isEditDialog: false,
      // 是否显示设置角色对话框
      isSetRoleDialog: false,
      // 添加用户表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加表单数据验证
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在3-10', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在6-16', trigger: 'blur' }
        ],
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        email: [{ required: true, validator: validateEmail, trigger: 'blur' }]
      },
      // 编辑用户表单数据
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      editFormRules: {
        mobile: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        email: [{ required: true, validator: validateEmail, trigger: 'blur' }]
      }
    }
  },
  methods: {
    handleSizeChange(size) {
      this.queryInfo.pagesize = size
      this.getUsers()
    },
    closeAddDialog() {
      this.$refs.addForm.resetFields()
      this.isAddDialog = false
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum = page
      this.getUsers()
    },
    // 添加添加用户对话框
    onShowAddDialog() {
      this.isAddDialog = true
    },
    // 显示用户信息
    onShowSetRoleDialog(user) {
      this.userInfo = user
      console.log(user)
      this.getRoleList()
      this.isSetRoleDialog = true
    },
    // 关闭编辑对话框
    closeEditDialog() {
      this.isEditDialog = false
      this.$refs.editForm.resetFields()
    },
    // 关闭设置角色对话框
    closeSetRoleDialog() {
      this.selectRole = null
      this.isSetRoleDialog = false
    },
    // 点击编辑按钮
    onEditUser() {
      this.$refs.editForm.validate(valida => {
        if (!valida) return false
        this.editUser()
      })
    },
    async onSetRole() {
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        { rid: this.selectRole }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      }
      this.$message.success('分配角色成功')
      this.getUsers()
      this.isSetRoleDialog = false
    },
    /**
     * 移出用户
     */
    onRemoveUser(id) {
      this.$confirm('是否永久删除该用户?', '提示', {
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeUser(id)
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    onChangeRole() {
      console.log(this)
    },
    onAddUser() {
      this.$refs.addForm.validate(valid => {
        if (valid) return
        this.addUser()
      })
    },
    // 获取角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roles = res.data
    },
    async removeUser(id) {
      const { data: res } = await this.$http.delete(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.getUsers()
      this.$message.success('删除成功')
    },
    // 显示编辑对话框
    async onShowEditDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.editForm = res.data
      this.isEditDialog = true
    },
    /**
     * 编辑用户
     */
    async editUser() {
      var params = {
        email: this.editForm.email,
        mobile: this.editForm.mobile
      }
      const { data: res } = await this.$http.put(
        `users/${this.editForm.id}`,
        params
      )
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      this.getUsers()
      this.isEditDialog = false
      this.$message.success('更新成功')
    },
    /**
     * 添加用户
     */
    async addUser() {
      const { data: res } = await this.$http.post('users', this.addForm)
      if (res.meta.status !== 201) {
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('创建成功')
      this.isAddDialog = false
      this.getUsers()
    },
    async getUsers() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取用户列表失败')
      }
      this.usersData = res.data.users
      this.total = res.data.total
    },
    async onStatusChange(row) {
      const { data: res } = await this.$http.put(
        `users/${row.id}/state/${row.mg_state}`
      )
      if (res.meta.status !== 200) {
        row.mg_state = !row.mg_state
        return this.$message.error(res.meta.msg)
      }
      this.$message.success('更新状态失败')
    }
  }
}
</script>

<style lang="less" scoped>
</style>
